package com.hcinfos.gsoo.ui;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Constants;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.User;
import com.hcinfos.gsoo.enity.ViewSuppDetail;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.interaze.DialogCallBack;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.LoginUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.UtilHttp;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

public class CommentActivity extends Activity implements OnClickListener {
	private TextView reg_tv;
	private ImageButton left_ib;
	private TextView center_tv;

	private EditText comment_et;
	private EditText averge_et;
	private Button submit_button;

	private RatingBar taste_ratingbar; // 口味
	private TextView taste_num;
	private RatingBar envir_ratingbar;
	private TextView envir_num;
	private RatingBar service_ratingbar;
	private TextView service_num;
	private float taste;
	private float envir;
	private float service;
	private Context context;

	private final int COMMENT_SUCCESS = 0x1120;
	private final int COMMENT_FAIL = COMMENT_SUCCESS + 1;
	private final int NOT_LOGIN = COMMENT_SUCCESS + 2;

	private final int LOGIN_RESULT_CODE = 0x4444;
	private Activity activity;

	private SharePreferenceUtil util;
	private User user;
	private Dialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		util = new SharePreferenceUtil(this, "setting");
		user = (User) util.loadObject("user");
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		dialog = DialogUtil.createWaitDialog(this, "提交评论中...");
		context = this;
		activity = this;
		setContentView(R.layout.activity_comment);
		initRes();
	}

	private void initRes() {
		left_ib = (ImageButton) findViewById(R.id.left_ib);
		left_ib.setOnClickListener(this);
		reg_tv = (TextView) findViewById(R.id.reg_tv);
		reg_tv.setVisibility(View.GONE);
		center_tv = (TextView) findViewById(R.id.center_tv);
		center_tv.setText("商铺点评");

		submit_button = (Button) findViewById(R.id.submit_button);
		submit_button.setOnClickListener(this);
		comment_et = (EditText) findViewById(R.id.comment_et);
		averge_et = (EditText) findViewById(R.id.averge_et);

		taste_ratingbar = (RatingBar) findViewById(R.id.taste_ratingbar);
		taste = taste_ratingbar.getRating();
		taste_num = (TextView) findViewById(R.id.taste_num);
		taste_num.setText(taste + "");
		taste_ratingbar
				.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

					@Override
					public void onRatingChanged(RatingBar ratingBar,
							float rating, boolean fromUser) {
						taste_num.setText(rating + "分");
						taste = rating;
					}
				});

		envir_ratingbar = (RatingBar) findViewById(R.id.envir_ratingbar);
		envir = envir_ratingbar.getRating();
		envir_num = (TextView) findViewById(R.id.envir_num);
		envir_num.setText(envir + "");
		envir_ratingbar
				.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

					@Override
					public void onRatingChanged(RatingBar ratingBar,
							float rating, boolean fromUser) {
						envir_num.setText(rating + "分");
						envir = rating;
					}
				});

		service_ratingbar = (RatingBar) findViewById(R.id.service_ratingbar);
		service = service_ratingbar.getRating();
		service_num = (TextView) findViewById(R.id.service_num);
		service_num.setText(service + "");
		service_ratingbar
				.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

					@Override
					public void onRatingChanged(RatingBar ratingBar,
							float rating, boolean fromUser) {
						service_num.setText(rating + "分");
						service = rating;
					}
				});
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_ib:
			Intent intent = new Intent(CommentActivity.this,
					CommentListActivity.class);
			intent.putExtra("detail", detail);
			startActivity(intent);
			finish();
			break;
		case R.id.submit_button:
			if (doCheck()) {
				dialog.show();
				doSubmit();
			}
			break;
		}
	}

	private ViewSuppDetail detail;

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		detail = (ViewSuppDetail) getIntent().getSerializableExtra("detail");
		if (detail == null)
			return;
		shopId = detail.getId();

	}

	private boolean doCheck() {
		if (taste == 0.0f) {
			Toast.makeText(context, "请对口味评价", 500).show();
			return false;
		}
		if (envir == 0.0f) {
			Toast.makeText(context, "请对环境评价", 500).show();
			return false;
		}
		if (service == 0.0f) {
			Toast.makeText(context, "请对服务评价", 500).show();
			return false;
		}
		if (comment_et.getText().toString().length() == 0) {
			comment_et.setHint("请填写你要评论的内容!谢谢");
			comment_et.setHintTextColor(Color.RED);
			return false;
		}
		if (averge_et.getText().toString().length() == 0) {
			averge_et.setHint("请填写人评消费!谢谢");
			averge_et.setHintTextColor(Color.RED);
			return false;
		}
		return true;
	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case COMMENT_SUCCESS:
				dialog.dismiss();
				Intent intent = new Intent(CommentActivity.this,
						CommentListActivity.class);
				intent.putExtra("detail", detail);
				startActivity(intent);
				finish();
				break;
			case NOT_LOGIN:

				if (user != null) {
					LoginUtil.isLoginSuccess(CommentActivity.this, handler);
				} else {
					dialog.dismiss();
					DialogUtil.createCallLoginDialog(CommentActivity.this,
							"请先登陆,再提交!", new DialogCallBack() {

								@Override
								public void viewClick() {

								}

								@Override
								public void ok() {
									Intent intent = new Intent(
											CommentActivity.this,
											LoginActivity.class);
									intent.putExtra("type",
											Constants.LOGIN_CODE);
									activity.startActivityForResult(intent,
											LOGIN_RESULT_CODE);

								}

								@Override
								public void init(Object obj) {

								}

								@Override
								public void cancel() {
									finish();
								}
							}, "登陆", "取消");
				}

				break;
			case LoginUtil.LOGIN_FAIL:
				dialog.dismiss();
				Toast.makeText(CommentActivity.this, "评论失败!", 500).show();
				break;
			case LoginUtil.LOGIN_SUCCESS:
				doSubmit();
				break;
			case COMMENT_FAIL:
				String error = "评论失败!";
				if (msg.obj != null) {
					error = msg.obj.toString();
				}
				dialog.dismiss();
				Toast.makeText(CommentActivity.this, error, 500).show();
				break;

			}
		};
	};

	private String shopId;
	private float sumScore;

	private void doSubmit() {

		sumScore = (taste + envir + service) / 3;

		HttpUtils http = UtilHttp.getHttpUtils(context);
		RequestParams params = new RequestParams();
		params.addBodyParameter("record.suppId", shopId);
		params.addBodyParameter("record.scoreSum", sumScore + "");
		params.addBodyParameter("record.score1", taste + "");
		params.addBodyParameter("record.score2", envir + "");
		params.addBodyParameter("record.score3", service + "");
		params.addBodyParameter("record.score4", sumScore + "");
		params.addBodyParameter("record.comment", comment_et.getText()
				.toString());
		params.addBodyParameter("record.consumptionPer", averge_et.getText()
				.toString());
		http.send(HttpRequest.HttpMethod.POST, Urls.SHOP_COMMENT_EDIT, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {

						try {
							String result = responseInfo.result;
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String message = obj.getString("message");
							if (state == 200) {
								Message msg = handler.obtainMessage();
								msg.what = COMMENT_SUCCESS;
								handler.sendMessage(msg);
							} else if (state == 198) {
								Message msg = handler.obtainMessage();
								msg.what = NOT_LOGIN;
								handler.sendMessage(msg);
							} else {
								Message msg = handler.obtainMessage();
								msg.what = COMMENT_FAIL;
								msg.obj = message;
								handler.sendMessage(msg);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(COMMENT_FAIL);
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						handler.sendEmptyMessage(COMMENT_FAIL);
					}
				});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
	}

	public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {

		Intent intent = new Intent(CommentActivity.this,
				CommentListActivity.class);
		intent.putExtra("detail", detail);
		startActivity(intent);
		finish();
		return super.onKeyDown(keyCode, event);
	};
}
